package cn.hty.mymsg.cron.xxl.utils;

import cn.hty.mymsg.common.constant.CommonConstant;
import cn.hty.mymsg.common.enums.RespStatusEnum;
import cn.hty.mymsg.common.vo.BasicResultVO;
import cn.hty.mymsg.cron.xxl.service.CronTaskService;
import cn.hty.mymsg.cron.xxl.constants.XxlJobConstant;
import cn.hty.mymsg.cron.xxl.enums.*;
import cn.hty.mymsg.domain.MessageTemplate;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import cn.hty.mymsg.cron.xxl.entity.XxlJobGroup;
import cn.hty.mymsg.cron.xxl.entity.XxlJobInfo;

import java.util.Date;
import java.util.Objects;

@Component
public class XxlJobUtils {
    @Value("${xxl.job.executor.appname}")
    private String appName;

    @Value("${xxl.job.executor.jobHandlerName}")
    private String jobHandlerName;

    @Autowired
    private CronTaskService cronTaskService;

    public XxlJobInfo buildXxlJobInfo(MessageTemplate messageTemplate){
        //获取时间表达式，如果没有就表示立刻执行，创建一个时间表达式给一定的延迟时间给xxl执行
        String scheduleConf = messageTemplate.getExpectPushTime();
        if (messageTemplate.getExpectPushTime().equals(String.valueOf(CommonConstant.FALSE))){
           scheduleConf = DateUtil.format(DateUtil.offsetSecond(new Date(), XxlJobConstant.DELAY_TIME), CommonConstant.CRON_FORMAT);
        }
        XxlJobInfo xxlJobInfo = XxlJobInfo.builder()
                .jobGroup(queryJobGroupId()).jobDesc(messageTemplate.getName())
                .author(messageTemplate.getCreator())
                .scheduleConf(scheduleConf)
                .scheduleType(ScheduleTypeEnum.CRON.name())
                .misfireStrategy(MisfireStrategyEnum.DO_NOTHING.name())
                .executorRouteStrategy(ExecutorRouteStrategyEnum.CONSISTENT_HASH.name())
                .executorHandler(XxlJobConstant.JOB_HANDLER_NAME)
                .executorParam(String.valueOf(messageTemplate.getId()))
                .executorBlockStrategy(ExecutorBlockStrategyEnum.SERIAL_EXECUTION.name())
                .executorTimeout(XxlJobConstant.TIME_OUT)
                .executorFailRetryCount(XxlJobConstant.RETRY_COUNT)
                .glueType(GlueTypeEnum.BEAN.name())
                .triggerStatus(CommonConstant.FALSE)
                .glueRemark(CharSequenceUtil.EMPTY)
                .glueSource(CharSequenceUtil.EMPTY)
                .alarmEmail(CharSequenceUtil.EMPTY)
                .childJobId(CharSequenceUtil.EMPTY).build();
        if (Objects.nonNull(messageTemplate.getCronTaskId())) {
            xxlJobInfo.setId(messageTemplate.getCronTaskId());
        }
        return xxlJobInfo;
    }

    /**
     * 根据就配置文件的内容获取jobGroupId，没有则创建
     *
     * @return
     */
    private Integer queryJobGroupId(){
        BasicResultVO<Integer> basicResultVO= cronTaskService.getGroupId(appName, jobHandlerName);
        if (Objects.isNull(basicResultVO.getData())){
            XxlJobGroup xxlJobGroup = XxlJobGroup.builder().appname(appName).addressType(CommonConstant.FALSE).title(jobHandlerName).build();
            if (RespStatusEnum.SUCCESS.getCode().equals(cronTaskService.createGroup(xxlJobGroup).getStatus())){
                return (Integer) cronTaskService.getGroupId(appName, jobHandlerName).getData();
            }
        }
        return basicResultVO.getData();
    }

}
